<script setup>
import { User, Lock, Loading } from '@element-plus/icons-vue'
import Color from 'element-plus/es/components/color-picker/src/utils/color';
import { login } from "@/api/admin/user"
import { reactive, ref, onBeforeUnmount, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { showMessage, startLoading } from '@/composables/utils';
import { setToken } from '@/composables/cookie/auth';
import { useUserStore } from '@/stores/user';

// 定义路由对象
const router = useRouter()
//按钮加载
const loading = ref(false)


/**
 * 表单校验
 * 1.表单引用            ref绑定el-form; 引用对象为 formRef(用来校验)
 * 2.定义校验规则        :rules绑定el-form; 给表单添加校验规则
 * 3.定义响应式表单对象  :model绑定el-form; 给表单绑定表单元素变量
 * 4.定义prop           prop绑定el-form-item; 给表单元素匹配校验规则
 * 5.定义v-model        v-model绑定表单元素el-input; 双向绑定
 */
const formRef = ref(null)
// 表单验证规则
const rules = {
    username: [
        {
            required: true,
            message: '用户名不能为空',
            trigger: 'blur'
        }
    ],
    password: [
        {
            required: true,
            message: '密码不能为空',
            trigger: 'blur',
        },
    ]
}
//定义响应式表单对象
const formValue = reactive({
    username: '',
    password: ''
})
//定义全局用户状态管理
const userStore = useUserStore()
//登录
const onSubmit = () => {
    console.log("=========UserLogin============")
    //验证 form表单字段
    formRef.value.validate((valid) => {
        if (!valid) { //输入格式不匹配
            console.log('form information formatter does not matched')
            return false
        }
        loading.value = true
        //发起异步请求
        login(formValue.username, formValue.password).then((res) => {
            console.log(res)
            if (res.success == true) {
                showMessage('Login Success!!!', 'success')
                let token = res.data.token
                setToken(token) //token存储到cookie中
                userStore.setUserInfo() //用户信息存储到全局状态管理中
                router.push('/admin/index')
            } else{
                let message = res.message
                showMessage(message, 'error')
            }
        }).finally(()=>{
            loading.value = false
        })
        
    })

}
//---------------------回车登录-----------------------
// 按回车键后，执行登录事件
function onKeyUp(e) {
    if (e.key == 'Enter') {
        onSubmit()
    }
}
// 添加键盘监听
onMounted(() => {
    document.addEventListener('keyup', onKeyUp)
})
// 移除键盘监听
onBeforeUnmount(() => {
    document.removeEventListener('keyup', onKeyUp)
})




</script>

<template>
    <!-- 使用 grid 网格布局，并指定列数为 2，高度占满全屏 -->
    <div class="grid grid-cols-2 h-screen">
        <!-- 默认先适配移动端，占两列，order 用于指定排列顺序，md 用于适配非移动端（PC 端）；背景色为xxx -->
        <div class="col-span-2 order-2 p-10 md:col-span-1 md:order-1 bgc-main">
            <div
                class="flex justify-center items-center h-full flex-col animate__animated animate__backInLeft animate__fast">
                <h2 class="font-bold text-4xl mb-7 text-white">KittenBlog 登录</h2>
                <p class="text-white">Spring Boot + Mybaits Plus + Vue 3.2 + Vite 4 开发的前后端分离博客。</p>
                <!-- 指定图片宽度为父级元素的 1/2 -->
                <img src="@/assets/use.png" class="w-1/2">
            </div>
        </div>
        <div class="col-span-2 order-1 md:col-span-1 md:order-2 bg-white">
            <div
                class="flex justify-center items-center h-full flex-col animate__animated animate__backInRight animate__fast">
                <h1 class="font-bold text-4xl mb-5">欢迎回来</h1>
                <!-- 设置 flex 布局，内容垂直水平居中，文字颜色，以及子内容水平方向 x 轴间距 -->
                <div class="flex items-center justify-center mb-7 text-gray-400 space-x-2">
                    <!-- 左边横线，高度为 1px, 宽度为 16，背景色设置 -->
                    <span class="h-[1px] w-16 bg-gray-200"></span>
                    <span>账号密码登录</span>
                    <!-- 右边横线 -->
                    <span class="h-[1px] w-16 bg-gray-200"></span>
                </div>
                <!-- 引入 Element Plus 表单组件，移动端设置宽度为 5/6，PC 端设置为 2/5 -->
                <el-form ref="formRef" :model="formValue" :rules="rules" class="w-5/6 md:w-2/5">
                    <el-form-item prop="username">
                        <!-- 输入框组件 -->
                        <el-input v-model="formValue.username" size="large" placeholder="请输入用户名" :prefix-icon="User"
                            clearable />
                    </el-form-item>
                    <el-form-item prop="password">
                        <!-- 密码框组件 -->
                        <el-input v-model="formValue.password"  size="large" type="password" placeholder="请输入密码"
                            :prefix-icon="Lock" clearable show-password />
                    </el-form-item>
                    <el-form-item>
                        <!-- 登录按钮，宽度设置为 100% -->
                        <el-button @click="onSubmit" :loading="loading" class="w-full" plain size="large"
                            color="rgb(254,200,91)">登录</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<style scoped>
.bgc-main {
    --tw-bg-opacity: 1;
    background-color: rgb(254 200 91 / var(--tw-bg-opacity));
}
</style>